$(function () {
    var way = getParam("way");
    var code = getParam("code");

    if (code) {
        thirdLogin(code)
    }

    //发送消息
    function send() {
        var message = document.getElementById('text').value;
        websocket.send(message);
    }

    if (way === 'third') {
        var iframe = $('<iframe>', {
            src: '', // 设置 iframe 的 URL
            frameborder: 0,
            width: '480px', // 设置宽度
            height: '630px' // 设置高度
        });
        iframe.attr('id', 'iam-auth')
        $("#loginDiv").html(iframe)

        iframe.on('load', function () {
            // 在 iframe 加载完成后执行的操作
            if (iframe[0].contentWindow.postMessage && window.addEventListener) {
                $(window).on('message', function (event) {
                    // 获取 postMessage 传递的 token
                    var code = event.originalEvent.data.ticket;
                    console.log('认证完成，通过 PostMessage 传递的 token: ', code);

                    thirdLogin(code, () => {
                        loadAuthPage(iframe)
                    })
                });
            }
        });

        loadAuthPage(iframe, (requestId) => {
            getWebsocket(requestId)
        })
        return
    }


    enabledAuthWays();
    validateKickout();
    validateRule();
    $('.imgcode').click(function () {
        var url = ctx + "captcha/captchaImage?type=" + captchaType + "&s=" + Math.random();
        $(".imgcode").attr("src", url);
    });
});

$.validator.setDefaults({
    submitHandler: function () {
        login();
    }
});

$("#ssoSubmit").click(function (e) {
    e.preventDefault();

    var clientName = $("#ways").val()
    if (!clientName) {
        $.modal.msg("请选择认证源");
        return
    }
    $.modal.loading($("#ssoSubmit").data("loading"));
    location.href = ctx + "callback?client_name=" + clientName
})

function enabledAuthWays() {
    $.ajax({
        type: "get",
        url: ctx + "enabledAuthWays",
        success: function (r) {
            if (r.code === web_status.SUCCESS) {
                var data = r.data

                var el = $("#ways");
                if (!data || data.length === 0) {
                    el.hide()
                    return
                }

                data.forEach(d => {
                    var $option = $(`<option value="${d.clientName}">${d.authName}</option>`);
                    el.append($option)
                })

                // data.forEach(d => {
                //     if (d.enabled) {
                //         var el = $("#" + d.name);
                //         el.show()
                //         el.on('click', function () {
                //             location.href = ctx + "callback?client_name=" + d.clientName
                //         })
                //     }
                // })
            }
        }
    });
}

function loadAuthPage(iframe, fn) {
    $.get("/third/getAuthPageUrl").done(function (res) {
        var data = res.data
        if (data.render === "0") {
            window.location.href = res.data.url
            return
        }

        if (data.issueType === 'SOAP' && fn) {
            fn(data.wsUrl, () => {
                loadAuthPage(iframe, fn)
            })
        }

        iframe.attr("src", res.data.url)
    });
}

function thirdLogin(code, fn) {
    $.modal.loading("登录中... 请稍后");

    $.ajax({
        type: "post",
        url: ctx + "third/login",
        data: {
            "code": code
        },
        success: function (r) {
            if (r.code === web_status.SUCCESS) {
                location.href = ctx + 'index';
            } else {
                $.modal.msg(r.msg);
                if (fn) {
                    fn()
                }
            }
            $.modal.closeLoading();
        }
    });
}

function login() {
    $.modal.loading($("#btnSubmit").data("loading"));
    var username = $.common.trim($("input[name='username']").val());
    var password = $.common.trim($("input[name='password']").val());
    var validateCode = $("input[name='validateCode']").val();
    var rememberMe = $("input[name='rememberme']").is(':checked');
    $.ajax({
        type: "post",
        url: ctx + "login",
        data: {
            "username": username,
            "password": password,
            "validateCode": validateCode,
            "rememberMe": rememberMe
        },
        success: function (r) {
            if (r.code === web_status.SUCCESS) {
                location.href = ctx + 'index';
            } else {
                $('.imgcode').click();
                $(".code").val("");
                $.modal.msg(r.msg);
            }
            $.modal.closeLoading();
        }
    });
}

function validateRule() {
    var icon = "<i class='fa fa-times-circle'></i> ";
    $("#signupForm").validate({
        rules: {
            username: {
                required: true
            },
            password: {
                required: true
            }
        },
        messages: {
            username: {
                required: icon + "请输入您的用户名",
            },
            password: {
                required: icon + "请输入您的密码",
            }
        }
    })
}

function validateKickout() {
    if (getParam("kickout") == 1) {
        layer.alert("<font color='red'>您已在别处登录，请您修改密码或重新登录</font>", {
                icon: 0,
                title: "系统提示"
            },
            function (index) {
                //关闭弹窗
                layer.close(index);
                if (top != self) {
                    top.location = self.location;
                } else {
                    var url = location.search;
                    if (url) {
                        var oldUrl = window.location.href;
                        self.location = oldUrl.substring(0, oldUrl.indexOf('?'));
                    }
                }
            });
    }
}

function getParam(paramName) {
    var reg = new RegExp("(^|&)" + paramName + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return decodeURI(r[2]);
    return null;
}

function getWebsocket(url, fn) {
    var websocket = null;

    //判断当前浏览器是否支持WebSocket
    if ('WebSocket' in window) {
        websocket = new WebSocket(url);
    } else {
        alert('Not support websocket')
        return
    }

    //连接发生错误的回调方法
    websocket.onerror = function (e) {
        console.log("error", e);
    };

    //连接成功建立的回调方法
    websocket.onopen = function (event) {
        console.log("open")
    }

    //接收到消息的回调方法
    websocket.onmessage = function (event) {
        if (!isJSON(event.data)) {
            console.log(event.data)
            return
        }

        var data = JSON.parse(event.data)
        $.modal.loading("登录中... 请稍后");

        $.ajax({
            type: "post",
            url: ctx + "third/soapLogin",
            data: data,
            success: function (r) {
                if (r.code === web_status.SUCCESS) {
                    websocket.close()
                    location.href = ctx + 'index';
                } else {
                    websocket.close()
                    if (fn) {
                        fn()
                    }
                    $.modal.msg(r.msg);
                }
                $.modal.closeLoading();
            }
        });
    }

    //连接关闭的回调方法
    websocket.onclose = function () {
        console.log("close")
    }

    //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
    window.onbeforeunload = function () {
        websocket.close();
    }

    //关闭连接
    function closeWebSocket() {
        websocket.close();
    }
}

function isJSON(str) {
    try {
        JSON.parse(str);
    } catch (e) {
        return false;
    }
    return true;
}